package com.yc.cloud.business;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.IdUtil;
import com.yc.cloud.common.utils.RedisUtil;
import com.yc.cloud.model.ImgVerification;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import static com.yc.cloud.common.constant.RedisConstant.SYS_VERIFY_IMG;

/**
 * @author 杨智杰
 * @since 2021/8/20 9:53
 */
@Service
public class SysUtilBusiness {

    @Resource
    private RedisUtil redisUtil;

    /**
     * 图片验证码有效时长(秒)
     */
    @Value("${auth-code-config.valid-time:300}")
    private Long authCodeValidTime;

    /**
     * 验证码图片宽度
     */
    @Value("${auth-code-config.width:150}")
    private Integer authCodeWidth;

    /**
     * 验证码图片高度
     */
    @Value("${auth-code-config.height:100}")
    private Integer authCodeHeight;

    /**
     * 获取一个图片验证码
     *
     * @return 图片验证码
     */
    public ImgVerification getVerificationCode() {
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(authCodeWidth, authCodeHeight);
        ImgVerification imgVerification = new ImgVerification()
                .setInDate(authCodeValidTime)
                .setImg(captcha.getImageBase64())
                .setSerial(IdUtil.fastUUID());
        redisUtil.set(SYS_VERIFY_IMG + imgVerification.getSerial(), captcha.getCode(), authCodeValidTime);
        return imgVerification;
    }

    /**
     * 图片验证码校验
     *
     * @param serial 验证码序号
     * @param code   验证码
     * @return
     */
    public Boolean verifyCode(String serial, String code) {
        if (code.equals((redisUtil.get(SYS_VERIFY_IMG + serial)))) {
            redisUtil.del(SYS_VERIFY_IMG + serial);
            return true;
        }
        return false;
    }


}
